package com.rrx.service;

import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@Controller
public class Method {
    @Resource
    UsersService usersService;
    // 小程序的唯一标示ID
    private static final String wxspAppid = "wx1482a5aea3785f9a";
    // 小程序的 app secret (在微信小程序管理后台获取)
    private static final String wxspSecret = "370cd68a3e99be23e587b43993eca3c1";
    // 授权（必填）
    private static final String grant_type = "authorization_code";



    public String MethodCode(String code){
        String parmas = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
       String oid="";
        try {
            URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?"+parmas);//接口地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();//建立链接
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            connection.disconnect();
            String json = sb.toString();
             oid = json.substring(json.indexOf("openid\":\"")+9, json.lastIndexOf("\""));


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return oid;
    }
}
